package per.turtle.common.security.aspect;

import cn.hutool.crypto.SecureUtil;
import lombok.RequiredArgsConstructor;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
import per.turtle.common.core.exception.CustomException;
import per.turtle.common.core.utils.ServletUtils;
import per.turtle.common.redis.service.RedisService;

import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

/**
 * 仅限服务间调用实现
 *
 * @author turtle
 */
@Aspect
@Component
@RequiredArgsConstructor
public class OnlyInterServiceAspect {

    public final static String CACHE_KEY = "only_inter_service-";

    private final static String PRE_STR = "JiuGao";

    private final static String POST_STR = "turtle";

    private final RedisService redisService;

    public static String getCheckStr(String s) {
        return SecureUtil.md5(PRE_STR + s + POST_STR);
    }

    @Around("@annotation(per.turtle.common.security.annotation.OnlyInterService)")
    public Object around(ProceedingJoinPoint point) throws Throwable {
        HttpServletRequest httpServletRequest = ServletUtils.getRequest();
        String keyId = ServletUtils.getHeaders(Objects.requireNonNull(httpServletRequest)).get(CACHE_KEY);
        if (getCheckStr(keyId).equals(redisService.getCacheObject(CACHE_KEY + keyId))) {
            redisService.deleteObject(CACHE_KEY + keyId);
            return point.proceed();
        } else {
            throw new CustomException("该接口不对外开放!");
        }
    }

}
